"""
自定义中间件
"""
import logging
import traceback

from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.utils.deprecation import MiddlewareMixin

import jwt
from rest_framework_jwt.utils import jwt_decode_handler

from account.models import Account

logger = logging.getLogger('log')


class AuthMiddleware(MiddlewareMixin):
    """
    验证token中间件
    """

    def process_request(self, request):
        """
        视图执行前
        """
        logger.info('AuthMiddleware: user-->{}'.format(request.user))
        return
        # token = request.headers.get('Authorization')
        # if token:
        #     token = token.replace('Bearer ', '')
        #     try:
        #         jwt_token = jwt_decode_handler(token)
        #         user = Account.objects.get(id=jwt_token.get('user_id'))
        #         request.user = user
        #         return
        #     except:
        #         return False
        # return


class AuthorBackend(ModelBackend):
    """
    重写登录注册的密码验证
    """

    def authenticate(self, request, username=None, password=None, **kwargs):

        user = Account.objects.filter(Q(username=username) | Q(phone=username) | Q(email=username)).first()
        if user and user.check_password(password):
            return user
        return None


def jwt_response_payload_handler(token, user, request):
    if user is not None:
        if user.is_active:
            superuser = str(user.is_superuser)
            return {'code': 200, 'data': {'resource_list': [], 'superuser': superuser, 'token': token,
                                          'user_id': user.id, 'user_name': user.username}}
        return {'code': 500, 'message': '用户已经被禁用'}
    # 否则就是用户名、密码有误
    return {'code': 406, 'message': '用户名或者密码错误'}
